import { defineStore } from 'pinia';
import storage from 'store';
import UaParser, { IResult as UaResult } from 'ua-parser-js';
import router from '@/router';
import { checkToken, getUserInfo, login, logout } from '@/api/user';
import { logout as ssoLogout } from '@/api/sso';
import { getCurrentIndexPath, getCurrentIndexPathByRedirect } from '@/libs/utils';
import { UserInfo, LoginForm } from '@/model';

export interface UserState {
  isLogin: boolean | null;
  userInfo: UserInfo;
  ua: UaResult;
  // 默认的路由路径
  defaultPath: Array<string>;
}

const defaultUserInfo = {
  id: '',
  token: '',
  name: '',
  username: '',
  avatar: '',
  menuTree: [],
};

export const useUserStore = defineStore({
  id: 'userStore',
  state: (): UserState => ({
    isLogin: null,
    userInfo: { ...defaultUserInfo },
    ua: new UaParser().getResult(),
    defaultPath: [],
  }),
  actions: {
    setUserInfo(payload: UserInfo) {
      this.userInfo = payload;
      storage.set('USER_ID', payload.id);
      storage.set('ACCESS_TOKEN', payload.token);
      storage.set('USERNAME', payload.username);
      storage.set('MENU_TREE', payload.menuTree);
      storage.set('NAME', payload.name);
    },
    resetUserInfo() {
      this.userInfo = { ...defaultUserInfo };
      storage.remove('USER_ID');
      storage.remove('ACCESS_TOKEN');
      storage.remove('USERNAME');
      storage.remove('MENU_TREE');
      storage.remove('NAME');
    },
    async getUserInfo() {
      const userId = storage.get('USER_ID');
      if (!userId) {
        getUserInfo(userId).then((res) => {
          this.setUserInfo(res);
        });
      }
    },
    async login(req: LoginForm) {
      await login(req).then((res) => {
        this.setUserInfo(res);
        // 判断登录成功后跳转到哪个路由，而且需要让菜单的展开选中状态对应上
        const { redirect }: { redirect?: string } = router.currentRoute.value.query;
        if (redirect) {
          this.defaultPath = getCurrentIndexPathByRedirect(
            storage.get('MENU_TREE'),
            redirect,
          );
          // 退出登录后可能用户的角色发生变化，这里判断重定向的路由是否还在重新登录后的权限列表中，如果没有，则默认第一个菜单页面
          if (this.defaultPath.length) {
            router.push({ path: redirect });
          } else {
            router.push({ path: '/main' });
          }
        } else {
          const indexPath = getCurrentIndexPath(storage.get('MENU_TREE'));
          this.defaultPath = indexPath;
          if (indexPath.length) {
            const defaultActive = indexPath[indexPath.length - 1];
            router.push({ path: defaultActive });
          } else {
            router.push({ path: '/main' });
          }
        }
      });
    },
    async logout() {
      const userId = storage.get('USER_ID');
      const { VITE_LOGIN_MODE } = import.meta.env;
      if (VITE_LOGIN_MODE === 'SSO') {
        ssoLogout()
          .then(() => {
            this.resetUserInfo();
            router.push({ name: 'Sso' });
          })
          .catch(() => {
            this.resetUserInfo();
            router.push({ name: 'Sso' });
          });
      } else {
        const { fullPath } = router.currentRoute.value;
        logout(userId)
          .then(() => {
            this.resetUserInfo();
            router.push({ name: 'Login', query: { redirect: fullPath } });
          })
          .catch(() => {
            this.resetUserInfo();
            router.push({ name: 'Login', query: { redirect: fullPath } });
          });
      }
    },
    async getUsername() {
      const username = storage.get('USERNAME');
      if (username) {
        return username;
      }
      this.getUserInfo().then();
      return storage.get('USERNAME');
    },
    async getName() {
      return storage.get('NAME');
    },
    async getMenu() {
      return storage.get('MENU_TREE');
    },
    async verification(token: string) {
      // 调用 token 验证接口
      return checkToken(token);
    },
    async getDefaultPath() {
      return this.defaultPath;
    },
  },
});
